import { createContext } from "react";
import { View, StyleSheet, Text, useWindowDimensions, Alert } from "react-native";
import { useSelector } from "react-redux";

// @ts-ignore
import DialogAndroid from "react-native-dialogs";
import NetworkState from "@/components/NetworkState";
import DrawerLayoutContent from "@/pages/VideoDisplay/DrawerLayoutContent";
import useDrawer from "@/hooks/useDrawer";

import globalMethods from "./GlobalMethodProvider";
import sm from "@/utils/ScheduleManage/operate";
import fso from "@/utils/FileOperate/operate";
import config from "@/config";
import navigation from "@/utils/navigation";
import { fetchEntryNetworkInfo } from "@/utils/entryNetworkInfoOperate";

import type { RootState } from "@/store";

/** context 数据给到调试组件使用 */
export const WidgetProviderContext = createContext<{
  /** 关闭抽屉组件 */
  closeDrawer: () => void;
} | null>(null);

// 页面部件组件
const WidgetProvider = () => {
  const reduxState = useSelector((state: RootState) => state);
  const reduxIndex = reduxState.index;
  const reduxCommon = reduxState.common;
  const networkState = reduxCommon.networkState ? (reduxIndex.isWebsocketConnect ? "3" : "2") : "1";

  const windowDimensions = useWindowDimensions();
  const { DrawerComp, openDrawer, closeDrawer, drawerVisible } = useDrawer({
    drawerWidth: windowDimensions.width * 0.8,
    drawerLockMode: "locked-open",
    renderNavigationView() {
      return (
        // 当前状态向下传递
        <WidgetProviderContext.Provider value={{ closeDrawer }}>
          <DrawerLayoutContent
            close={() => {
              closeDrawer();
            }}
          />
        </WidgetProviderContext.Provider>
      );
    }
  });

  /** 网络状态点击 */
  const networkStateClick = () => {
    globalMethods.$showModalBox({
      title: "提示",
      contentPosition: "center",
      showMiddleBtn: true,
      middleBtnText: "调试",
      contentComponent() {
        return networkTipComp;
      },
      closeBtnText: "网络测试",
      onClose() {
        // 设备的浏览器版本太低不支持直接打开后台网页
        // Linking.openURL(config.serveUrl.businessUrl);

        navigation.replace("NetworkDebug", {
          url: config.serveUrl.businessUrl
        });
      },
      onMiddle() {
        openDrawer();
      },
      bigBtnListPosition: "middle",
      bigBtnList() {
        return [
          {
            text: "一键重置",
            textStyle: {
              color: "red"
            },
            onClick() {
              Alert.alert("警告", "确定要一键重置功能?", [
                { text: "取消", style: "cancel" },
                {
                  text: "确定",
                  onPress: async () => {
                    try {
                      fso.info("一键重置");
                      const clearRes = await sm.clearNativeData(true);
                      fso.info("新版数据一键重置: ", clearRes ? "成功" : "失败");
                      const clearOldRes = await sm.clearOldAppNativeData();
                      fso.info("旧版app素材文件清理: ", clearOldRes ? "成功" : "失败");
                      if (clearRes) {
                        sm.playPolyfill();
                      } else {
                        globalMethods.$error("一键重置失败");
                      }
                    } catch (err) {
                      console.log("err: ", err);
                      fso.info("一键重置发生了错误: ", err);
                      globalMethods.$error("一键重置失败: " + err);
                    } finally {
                      globalMethods.$hideModalBox();
                    }
                  }
                }
              ]);
            }
          },
          {
            text: "设置设备编号",
            onClick() {
              DialogAndroid.prompt("获取设备信息", "输入设备编号", {
                defaultValue: "",
                cancelable: false
              })
                .then((res: any) => {
                  const { action, text } = res;
                  if (action === DialogAndroid.actionPositive) {
                    fetchEntryNetworkInfo(text, true);
                  }
                })
                .catch((err: any) => {
                  console.log("err: ", err);
                })
            }
          }
        ];
      }
    });
  };

  /** 网络信息提示组件 */
  const networkTipComp = (
    <View style={{ rowGap: 10 }}>
      <View style={styles.networkItem}>
        <NetworkState state="1" content={reduxIndex.entryNetworkInfo?.code || ""} />
        <Text> 表示没有网络</Text>
      </View>
      <View style={styles.networkItem}>
        <NetworkState state="2" content={reduxIndex.entryNetworkInfo?.code || ""} />
        <Text> 表示有网络但是没有连接到后台</Text>
      </View>
      <View style={styles.networkItem}>
        <NetworkState state="3" content={reduxIndex.entryNetworkInfo?.code || ""} />
        <Text> 表示网络正常</Text>
      </View>
    </View>
  );

  // 左下角网络圆点或设备编号
  const NetworkStateComp = (
    <View style={styles.networkStateContainer}>
      <NetworkState
        state={networkState}
        content={reduxIndex.entryNetworkInfo?.code || ""}
        onClick={networkStateClick}
      />
    </View>
  );

  return (
    <>
      {/* 右下角的信号灯 */}
      {/* {NetworkStateComp} */}

      {/* 全屏抽屉, 放调试菜单 */}
      {DrawerComp}
    </>
  );
};

const styles = StyleSheet.create({
  networkStateContainer: {
    position: "absolute",
    bottom: 8,
    left: 4,
    zIndex: 9999
  },
  networkItem: {
    flexDirection: "row",
    alignItems: "center"
  }
});

export default WidgetProvider;
